<template>
  <view class="container">
    <!-- 全屏初始化加载动画 -->
    <view class="initial-loading-overlay" v-if="initialLoading">
      <view class="initial-loading-content">
        <view class="initial-loading-spinner"></view>
        <text class="initial-loading-text">正在加载...</text>
      </view>
    </view>
    <!-- 顶部搜索框 -->
    <view class="search-header" :class="{ 'search-fixed': isSearchFixed }">
      <uni-search-bar
        v-model="searchKeyword"
        placeholder="搜索商品"
        @confirm="onSearchInput"
        @input="onSearchInput"
        @clear="onSearchClear"
        @cancel="onSearchCancel"
        clearButton="auto"
        radius="25"
      />
    </view>

    <!-- 轮播图 -->
    <view class="banner-section" :class="{ 'banner-margin': isSearchFixed }">
      <swiper
        class="swiper"
        circular
        :indicator-dots="true"
        :autoplay="true"
        :interval="3000"
        :duration="1000"
        @change="change"
      >
        <swiper-item v-for="(item, index) in bannerList" :key="index">
          <image :src="item.image" mode="aspectFill" class="banner-image" @click="onBannerClick(item)" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 公告栏 -->
    <view class="notice-section">
      <uni-notice-bar
        :text="noticeText"
        :show-close="false"
        :show-icon="true"
        :single="false"
        :scrollable="true"
        background-color="#f8f9fa"
        color="#333"
        :speed="50"
      />
    </view>

    <!-- 商品列表 -->
    <view class="products-section">
      <view class="products-waterfall">
        <!-- 左列 -->
        <view class="waterfall-column">
          <view
            v-for="(product, index) in leftColumnProducts"
            :key="product.id"
            class="product-card"
            @click="goToDetail(product)"
          >
            <view class="product-image-container">
              <image
                :src="product.mainImageUrl || '/static/default-product.png'"
                mode="widthFix"
                class="product-image"
              />
              <!-- 促销标签 -->
              <view v-if="product.originalIndex % 5 === 0" class="promo-tag">
                <text class="promo-text">自营</text>
              </view>
            </view>
            <view class="product-content">
              <view class="product-title">
                <text class="product-name">{{ product.productName }}</text>
              </view>
              <view class="product-pricing">
                <text class="current-price">¥{{ product.sellingPrice / 100 }}</text>
                <!-- <text v-if="product.originalIndex % 3 === 0" class="original-price"
                  >¥{{ ((product.sellingPrice / 100) * 1.2).toFixed(0) }}</text
                > -->
              </view>
              <!-- 销售用户显示佣金信息 -->
              <view v-if="userInfo.userType === 'sales'" class="commission-info">
                <text class="commission-text">佣金 ¥{{ product.salesCommission / 100 || 0 }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 右列 -->
        <view class="waterfall-column">
          <view
            v-for="(product, index) in rightColumnProducts"
            :key="product.id"
            class="product-card"
            @click="goToDetail(product)"
          >
            <view class="product-image-container">
              <image
                :src="product.mainImageUrl || '/static/default-product.png'"
                mode="widthFix"
                class="product-image"
              />
              <!-- 促销标签 -->
              <view v-if="product.originalIndex % 5 === 0" class="promo-tag">
                <text class="promo-text">自营</text>
              </view>
            </view>
            <view class="product-content">
              <view class="product-title">
                <text class="product-name">{{ product.productName }}</text>
              </view>
              <view class="product-pricing">
                <text class="current-price">¥{{ product.sellingPrice / 100 }}</text>
                <text v-if="product.originalIndex % 3 === 0" class="original-price"
                  >¥{{ ((product.sellingPrice / 100) * 1.2).toFixed(0) }}</text
                >
              </view>
              <!-- 销售用户显示佣金信息 -->
              <view v-if="userInfo.userType === 'sales'" class="commission-info">
                <text class="commission-text">佣金 ¥{{ product.salesCommission / 100 || 0 }}</text>
              </view>
              <!-- 评价信息 -->
              <view v-if="product.originalIndex % 4 !== 3" class="product-reviews">
                <text class="review-count">{{ Math.floor(Math.random() * 1000) + 100 }}人评价</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !loading">
      <text class="load-text">上拉加载更多...</text>
    </view>

    <!-- 加载动画 -->
    <view class="loading-container" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">正在加载...</text>
    </view>

    <!-- 全部加载完成 -->
    <view class="no-more" v-if="!hasMore && displayProducts.length > 0">
      <text class="no-more-text">已全部加载完成</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onReachBottom, onPageScroll, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import { getUserInfo, addAuthStateListener, removeAuthStateListener } from '@/utils/auth';
import request from '@/utils/request';

// 商品接口类型定义
interface ProductImage {
  ossId: string;
  fileName: string;
  originalName: string;
  fileSuffix: string;
  url: string;
  ext1: string;
  createTime: string;
  createBy: number;
  createByName: string;
  service: string;
  businessType: string;
  businessId: string;
}

interface Product {
  id: string;
  productName: string;
  sellingPrice: number;
  salesCommission: number | null;
  mainImage: ProductImage | null;
  mainImageUrl: string | null;
  mainImageId: string | null;
}

interface ProductListResponse {
  total: number;
  rows: Product[];
  code: number;
  msg: string;
}

// 公告接口类型定义
interface NoticeItem {
  noticeId: number;
  noticeImageUrl: string;
  noticeTitle: string;
  noticeType: string;
}

interface NoticeListResponse {
  code: number;
  msg: string;
  data: NoticeItem[];
}

// 轮播图数据类型
interface BannerItem {
  noticeId?: number;
  image: string;
  title: string;
}

// 用户信息状态
const userInfo = ref({
  userType: 'normal',
});

// 检查登录状态
const checkLoginStatus = () => {
  const storedUserInfo = getUserInfo();
  console.log('storedUserInfo', storedUserInfo);
  if (storedUserInfo) {
    userInfo.value = {
      ...storedUserInfo,
      // userType: 'sales'
    };
  } else {
    userInfo.value = {
      userType: 'normal',
    };
  }
};

// 搜索相关
const searchKeyword = ref('');
const isSearchFixed = ref(false);

// 公告数据
const noticeList = ref<NoticeItem[]>([]);
const noticeText = ref('正在加载公告...');

// 轮播图数据
const bannerList = ref<BannerItem[]>([
  {
    image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=800&h=400&fit=crop&crop=center',
    title: '正在加载轮播图...',
  },
]);

// 轮播图配置
const current = ref(0);

// 商品数据状态
const productList = ref<Product[]>([]);
const total = ref(0);
const loading = ref(false);
const hasMore = ref(true);
const refreshing = ref(false);

// 页面初始化加载状态
const initialLoading = ref(false);

// 分页参数
const pageNum = ref(1);
const pageSize = ref(10);

// 计算显示的商品列表（用于搜索过滤）
const displayProducts = computed(() => {
  if (!searchKeyword.value) {
    return productList.value;
  }
  return productList.value.filter((product) => {
    return product.productName.includes(searchKeyword.value);
  });
});

// 简单的瀑布流分配算法
const waterfallColumns = computed(() => {
  const products = displayProducts.value;
  const leftColumn = [];
  const rightColumn = [];

  // 简单的交替分配策略
  products.forEach((product, index) => {
    const productWithIndex = {
      ...product,
      originalIndex: index,
    };

    // 交替分配到左右两列
    if (index % 2 === 0) {
      leftColumn.push(productWithIndex);
    } else {
      rightColumn.push(productWithIndex);
    }
  });

  return {
    left: leftColumn,
    right: rightColumn,
  };
});

// 瀑布流布局 - 左列商品
const leftColumnProducts = computed(() => {
  return waterfallColumns.value.left;
});

// 瀑布流布局 - 右列商品
const rightColumnProducts = computed(() => {
  return waterfallColumns.value.right;
});

// 获取公告数据
const getNoticeData = async () => {
  try {
    console.log('开始获取公告数据...');

    const response = await request<NoticeListResponse>({
      url: '/notice/list',
      method: 'GET',
    });

    console.log('公告数据响应:', response);

    if (response.code === 200 && response.data) {
      noticeList.value = response.data;

      // 根据类型分离数据
      const banners = response.data.filter((item) => item.noticeType === '3');
      const notices = response.data.filter((item) => item.noticeType === '2');

      // 更新轮播图数据
      if (banners.length > 0) {
        bannerList.value = banners.map((banner) => ({
          noticeId: banner.noticeId,
          image:
            banner.noticeImageUrl ||
            'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=800&h=400&fit=crop&crop=center',
          title: banner.noticeTitle || '轮播图',
        }));
      }

      // 更新公告文本（如果有多条公告，拼接显示）
      if (notices.length > 0) {
        const noticeTexts = notices.map((notice) => notice.noticeTitle).filter((title) => title);
        if (noticeTexts.length > 0) {
          // 多条公告用转义字符分隔，形成滚动显示效果
          // 使用多个&nbsp;不间断空格来分隔
          noticeText.value = noticeTexts.join('\u00A0\u00A0\u00A0\u00A0\u00A0');
        }
      } else {
        noticeText.value = '暂无公告';
      }

      console.log('公告数据处理完成:', {
        banners: bannerList.value,
        noticeText: noticeText.value,
        totalNotices: response.data.length,
      });
    } else {
      console.warn('获取公告数据失败:', response.msg);
      // 保持默认数据
      noticeText.value = '获取公告失败，请稍后重试';
    }
  } catch (error) {
    console.error('获取公告数据异常:', error);
    noticeText.value = '网络错误，无法获取公告';
  }
};

// 获取商品列表
const getProductList = async (productName: string = '', isLoadMore: boolean = false) => {
  try {
    loading.value = true;

    // 如果不是加载更多，重置页码
    if (!isLoadMore) {
      pageNum.value = 1;
    }

    const response = await request<ProductListResponse>({
      url: '/product/list',
      method: 'GET',
      data: {
        productName: productName,
        pageNum: pageNum.value,
        pageSize: pageSize.value,
      },
    });

    if (response.code === 200) {
      if (isLoadMore) {
        // 加载更多时，追加到现有列表
        productList.value = [...productList.value, ...response.rows];
      } else {
        // 首次加载或搜索时，替换列表
        productList.value = response.rows;
      }

      total.value = response.total;

      // 判断是否还有更多数据
      hasMore.value = productList.value.length < response.total;

      console.log('商品列表加载完成:', {
        currentPage: pageNum.value,
        pageSize: pageSize.value,
        currentCount: productList.value.length,
        total: response.total,
        hasMore: hasMore.value,
      });
    } else {
      uni.showToast({
        title: response.msg || '获取商品列表失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
    });
  } finally {
    loading.value = false;
  }
};

// 轮播图切换
const change = (e: any) => {
  current.value = e.detail.current;
};

// 轮播图点击事件
const onBannerClick = (banner: BannerItem) => {
  console.log('轮播图点击:', banner);

  if (banner.noticeId) {
    // 跳转到公告详情页
    uni.navigateTo({
      url: `/pages/notice/detail?id=${banner.noticeId}`,
    });
  } else {
    uni.showToast({
      title: '暂无详情信息',
      icon: 'none',
      duration: 2000,
    });
  }
};

// 搜索输入
const onSearchInput = (value: any) => {
  // console.log(value);
  // console.log('搜索关键词:', searchKeyword.value);
  searchKeyword.value = value;
  // 调用接口搜索
  getProductList(searchKeyword.value);
};

// 搜索清除
const onSearchClear = () => {
  searchKeyword.value = '';
  console.log('搜索已清除');
  // 重新获取全部商品
  getProductList();
};

// 搜索取消
const onSearchCancel = () => {
  searchKeyword.value = '';
  console.log('搜索已取消');
  // 重新获取全部商品
  getProductList();
};

// 跳转到商品详情
const goToDetail = (product: any) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${product.id}`,
  });
};

// 加载更多商品
const loadMore = () => {
  if (loading.value || !hasMore.value) return;

  console.log('加载更多商品，当前页码:', pageNum.value);

  // 增加页码
  pageNum.value++;

  // 调用接口加载更多数据
  getProductList(searchKeyword.value, true);
};

// 下拉刷新
const onRefresh = async () => {
  if (refreshing.value) return;

  console.log('下拉刷新');
  refreshing.value = true;

  try {
    // 重置分页参数
    pageNum.value = 1;
    hasMore.value = true;

    // 并行刷新公告数据和商品列表
    await Promise.all([getNoticeData(), getProductList(searchKeyword.value, false)]);

    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1000,
    });
  } catch (error) {
    console.error('刷新失败:', error);
  } finally {
    refreshing.value = false;
  }
};

// 页面滚动监听
onPageScroll((e) => {
  const scrollTop = e.scrollTop;
  isSearchFixed.value = scrollTop > 200; // 滚动超过200px时吸顶
});

// 页面触底加载更多
onReachBottom(() => {
  loadMore();
});

// 下拉刷新监听
onPullDownRefresh(async () => {
  await onRefresh();
  uni.stopPullDownRefresh();
});

// 认证状态监听器
const authStateListener = () => {
  checkLoginStatus();
};

// onMounted(() => {
//   // 检查登录状态
//   checkLoginStatus();
//   // 添加认证状态监听器
//   addAuthStateListener(authStateListener);
// });

onUnmounted(() => {
  // 移除认证状态监听器
  // removeAuthStateListener(authStateListener);
});

// 页面显示时重新检查登录状态
onShow(async () => {
  // 显示全屏加载动画
  initialLoading.value = true;

  try {
    // 检查登录状态，未登录则跳转到登录页
    // const storedUserInfo = getUserInfo();
    // if (!storedUserInfo) {
    //   console.log('商城页面：用户未登录，跳转到登录页');

    //   // 延迟一下让用户看到加载状态
    //   await new Promise((resolve) => setTimeout(resolve, 800));

    //   uni.navigateTo({
    //     url: '/pages/user/login',
    //   });
    // } else {
    //   // 并行获取公告数据和商品列表
    //   await Promise.all([getNoticeData(), getProductList()]);
    //   initialLoading.value = false;
    // }
    await Promise.all([getNoticeData(), getProductList()]);
    initialLoading.value = false;
    checkLoginStatus();
  } catch (error) {
    console.error('页面初始化失败:', error);
    initialLoading.value = false;
  }
});
</script>

<style scoped>
.container {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
    'Helvetica Neue', Helvetica, Arial, sans-serif;
}

/* 搜索框样式优化 */
.search-header {
  position: relative;
  z-index: 100;
  background: rgba(255, 255, 255, 0.95);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 20rpx;
}

.search-header.search-fixed {
  position: fixed;
  top: 0px;
  left: 0;
  right: 0;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
}

/* 轮播图样式优化 */
.banner-section {
  position: relative;
  height: 420rpx;
  margin: 12rpx;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.15);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.banner-section.banner-margin {
  margin-top: 120rpx;
}

.swiper {
  height: 100%;
  border-radius: 24rpx;
}

.banner-image {
  width: 100%;
  height: 100%;
  border-radius: 24rpx;
  transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.banner-image:active {
  transform: scale(0.96);
}

/* 公告栏样式优化 */
.notice-section {
  /* background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); */
  margin: 12rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

/* 商品列表瀑布流样式 */
.products-section {
  padding: 0 12rpx 40rpx;
}

.products-waterfall {
  display: flex;
  gap: 12rpx;
  align-items: flex-start;
  min-height: 100vh;
}

.waterfall-column {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 确保两列高度平衡的辅助样式 */
.waterfall-column:first-child {
  margin-right: 6rpx;
}

.product-card {
  width: 100%;
  background: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  margin-bottom: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  border: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.product-card:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12);
}

/* 商品图片容器 */
.product-image-container {
  position: relative;
  overflow: hidden;
}

.product-image {
  width: 100%;
  display: block;
  border-radius: 8rpx 8rpx 0 0;
}

/* 促销标签 */
.promo-tag {
  position: absolute;
  top: 8rpx;
  left: 8rpx;
  background: linear-gradient(135deg, #ff6600 0%, #ff8800 100%);
  border-radius: 4rpx;
  padding: 2rpx 8rpx;
}

.promo-text {
  font-size: 18rpx;
  color: #fff;
  font-weight: 500;
}

/* 商品内容区域 */
.product-content {
  padding: 12rpx;
}

.product-title {
  margin-bottom: 8rpx;
}

.product-name {
  font-size: 24rpx;
  color: #333;
  font-weight: 400;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
}

.product-desc {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 20rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 400;
}

/* 价格区域 */
.product-pricing {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  margin-bottom: 6rpx;
}

.current-price {
  font-size: 28rpx;
  color: #ff6600;
  font-weight: 600;
}

.original-price {
  font-size: 20rpx;
  color: #999;
  text-decoration: line-through;
  font-weight: 400;
}

/* 佣金信息 */
.commission-info {
  margin-bottom: 6rpx;
}

.commission-text {
  font-size: 20rpx;
  color: #ff6600;
  background: #fff7e6;
  padding: 2rpx 6rpx;
  border-radius: 4rpx;
  border: 1rpx solid #ffd591;
}

/* 评价信息 */
.product-reviews {
  margin-top: 4rpx;
}

.review-count {
  font-size: 20rpx;
  color: #999;
  font-weight: 400;
}

.product-tags {
  display: flex;
  flex-wrap: wrap;
  /* gap: 8rpx; */
}

.product-tag {
  font-size: 20rpx;
  color: #ff6b35;
  background: linear-gradient(135deg, #fff5f0 0%, #ffe8e0 100%);
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  border: 1rpx solid rgba(255, 107, 53, 0.2);
  font-weight: 500;
}

/* 加载状态样式优化 */
.load-more,
.no-more {
  text-align: center;
  padding: 24rpx 0 48rpx;
}

.load-text,
.no-more-text {
  font-size: 28rpx;
  color: #888;
  font-weight: 500;
  letter-spacing: 0.02em;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
}

.loading-spinner {
  width: 48rpx;
  height: 48rpx;
  border: 4rpx solid rgba(255, 107, 53, 0.1);
  border-top: 4rpx solid #ff6b35;
  border-radius: 50%;
  animation: spin 1.2s cubic-bezier(0.4, 0, 0.2, 1) infinite;
  margin-bottom: 24rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #888;
  font-weight: 500;
  letter-spacing: 0.02em;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 底部导航栏样式优化 */
:deep(.uni-tabbar) {
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.12);
  border-top: 1rpx solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.95);
}

:deep(.uni-tabbar-item) {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.uni-tabbar-item.active) {
  transform: translateY(-4rpx);
}

:deep(.uni-tabbar-item.active .uni-tabbar-item-text) {
  font-weight: 600;
  transform: scale(1.05);
}

:deep(.uni-tabbar-item-icon) {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.uni-tabbar-item.active .uni-tabbar-item-icon) {
  transform: scale(1.15);
}

/* 全屏加载动画优化 */
.initial-loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #ffffff;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.initial-loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.initial-loading-spinner {
  width: 70rpx;
  height: 70rpx;
  border: 6rpx solid rgba(255, 102, 0, 0.2);
  border-top: 6rpx solid #ff6600;
  border-radius: 50%;
  animation: initialSpin 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;
  margin-bottom: 40rpx;
}

.initial-loading-text {
  font-size: 32rpx;
  color: #ff6600;
  font-weight: 600;
  letter-spacing: 0.02em;
}

@keyframes initialSpin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 搜索框内部样式优化 */
:deep(.uni-searchbar) {
  border-radius: 20rpx;
  overflow: hidden;
}

:deep(.uni-searchbar__box) {
  background: rgba(248, 249, 250, 0.8);
  border-radius: 20rpx;
  border: 1rpx solid rgba(0, 0, 0, 0.05);
}

:deep(.uni-searchbar__text-input) {
  font-weight: 500;
  color: #333;
}

/* 轮播图指示器优化 */
:deep(.uni-swiper-dot-box) {
  bottom: 20rpx;
}

:deep(.uni-swiper__dot) {
  background: rgba(255, 255, 255, 0.4);
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

:deep(.uni-swiper__dot-active) {
  background: #fff;
  transform: scale(1.2);
}
</style>
